<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" :align-center="true" width="50%" :title="`简历分组`">
    <el-form
      ref="wgFormRef"
      :disabled="dialogData.isView"
      :model="dialogData.itemInfo"
      :rules="rules"
      label-width="120px"
      label-suffix=" :"
      :hide-required-asterisk="dialogData.isView"
    >
      <div class="form-wrapper">
        <div class="left-box">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>设置分组</span>
                <el-button type="primary" :icon="CirclePlus" @click="handleSetGroup">保存设置</el-button>
              </div>
            </template>
            <div class="text item">
              <el-select v-model="dialogData.itemInfo.id" class="m-2" placeholder="Select" size="large" style="width: 100%">
                <el-option v-for="item in dialogData.groups" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </el-card>
        </div>
        <div class="right-box">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>新建分组</span>
                <el-button type="primary" :icon="CirclePlus" @click="handleSaveGroup">新建分组</el-button>
              </div>
            </template>
            <div class="text item">
              <el-alert title="提示信息" description="分组不存在，可以先创建一个" type="info" :closable="false" show-icon />
              <el-form-item></el-form-item>
              <el-form-item label="分组名称" prop="name">
                <el-input
                  placeholder="请填分组名称"
                  v-model="dialogData.itemInfo.name"
                  size="large"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item label="分组图标">
                <el-input
                  placeholder="分组图标，可参考官方文档"
                  v-model="dialogData.itemInfo.icon"
                  size="large"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </div>
          </el-card>
        </div>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { getOptTitle, OptEnum } from "@/biz/eenum/appEnum";
import { IdsDialogParam } from "@/biz/interface/DialogType";
import { CompanyGroupEntity } from "@/biz/interface/WorkerType";
import { CirclePlus } from "@element-plus/icons-vue";
import { getWorkerGroupsApi, saveCompanyGroupApi, setCompanyGroupApi, setCompanyWorkerGroupApi } from "@/api/modules/cpyswk/wk";

//页面的数据, ids 是通过主键修改
// workerId， 是对单个工友的分组
interface WorkerGroupDialogOption extends IdsDialogParam {
  //弹出表单的标题
  title: string;
  //是否是查看状态，查看状态是不可以提交数据
  isView: boolean;

  //工友 - 操作单个工友
  workerId?: string;
  groups: [];
  //当前的数据对象
  itemInfo: CompanyGroupEntity;
}

//提交按钮，避免多次提交
const btnLoading = ref(false);
//弹出框的参数
const dialogVisible = ref(false);
//当前表单数据在这里初始化
const dialogData = reactive<WorkerGroupDialogOption>({
  optType: OptEnum.UNKNOW,
  title: "",
  ids: [],
  groups: [],
  isView: false,
  itemInfo: {
    name: "",
    icon: ""
  }
});

//数据较验
const rules = reactive({
  name: [{ required: true, message: "请填写分组名称", trigger: "blur" }]
});

// 接收父组件传过来的参数
const acceptParams = (params: WorkerGroupDialogOption): void => {
  dialogData.optType = params.optType;
  dialogData.ids = params.ids;
  dialogData.isView = dialogData.optType === OptEnum.VIEW;
  dialogData.title = getOptTitle(dialogData.optType);
  dialogData.workerId = params.workerId;

  if (dialogData.optType === OptEnum.CREATE) {
    initItemInfo();
  }

  //获取企业当前的分组
  getCompanyGrups();

  dialogVisible.value = true;
};

//初始化页面的数据
const initItemInfo = (): void => {
  dialogData.itemInfo = {
    name: "",
    icon: ""
  };
};

const getCompanyGrups = async () => {
  let { data } = await getWorkerGroupsApi({});
  if (data) {
    dialogData.groups = data as unknown as [];
  }
};

//设置分组
const handleSetGroup = async () => {
  if (dialogData.itemInfo.id) {
    //提交数据
    try {
      //提交数据
      let res = {};
      if (dialogData.ids) {
        res = await setCompanyGroupApi({
          groupId: dialogData.itemInfo.id,
          ids: dialogData.ids
        });
      } else if (dialogData.workerId) {
        res = await setCompanyWorkerGroupApi({
          groupId: dialogData.itemInfo.id,
          workerId: dialogData.workerId
        });
      }
      if (res.data) {
        ElMessage.success({ message: `分组设置成功` });
        //刷新列表数据
        emits("refresh-list");
        dialogVisible.value = false;
      }
    } catch (error) {
    } finally {
      btnLoading.value = false;
    }
  } else {
    ElMessage.error("请选择要设置的组");
  }
};

//新增分组
const wgFormRef = ref<FormInstance>();
const handleSaveGroup = () => {
  btnLoading.value = true;
  wgFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      //提交数据
      let res = await saveCompanyGroupApi({
        ...dialogData.itemInfo
      });
      if (res.data) {
        ElMessage.success({ message: `保存成功` });
        //刷新列表数据
        getCompanyGrups();
        emits("refresh-list");
        // dialogVisible.value = false;
      }
    } catch (error) {
    } finally {
      btnLoading.value = false;
    }
  });
};

//页面事件
const emits = defineEmits(["refresh-list"]);

//页面参数
defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss">
.form-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-around;

  margin-top: 20px;
  // border: 1px solid red;

  .left-box {
    width: 50%;
    height: 320px;
    // border: 1px solid red;
  }

  .right-box {
    flex: 1;
    height: 320px;
    margin-left: 5px;
    // border: 1px solid red;
  }
}

.box-card {
  height: 300px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
